<template>
	<view class="page">
		<view class="login-form">
			<view class="title"><text>样本对比管理</text></view>

			<uni-forms ref="loginForm" :modelValue="loginFormData" :rules="rules">
				<uni-forms-item label="姓名" name="name"><uni-easyinput type="text" v-model="loginFormData.name" placeholder="请输入姓名" /></uni-forms-item>
				<uni-forms-item label="密码" name="password"><uni-easyinput type="password" v-model="loginFormData.password" placeholder="请输入密码" /></uni-forms-item>
				<uni-forms-item name="role" label="角色"><uni-data-checkbox v-model="loginFormData.role" :localdata="roles"></uni-data-checkbox></uni-forms-item>
			</uni-forms>

			<i-button shape="circle" width="500rpx" height="80rpx" margin="30rpx auto" @click="checkLogin">登录</i-button>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, getCurrentInstance } from 'vue'
import { onLoad, onShow, onReady } from '@dcloudio/uni-app'

const uniIdCo = uniCloud.importObject('uni-id-co')

const loginLoading = ref(false)

const loginFormData = ref({
	username: '',
	password: '',
	role: ''
})

const roles = ref([
	{
		text: '我是老师',
		value: 'teacher'
	},
	{
		text: '我是学生',
		value: 'student'
	}
])

const rules = ref({
	name: {
		rules: [
			// 校验 name 不能为空
			{
				required: true,
				errorMessage: '请填写姓名'
			}
		],
		// 当前表单域的字段中文名，可不填写
		label: '姓名',
		validateTrigger: 'submit'
	},
	password: {
		rules: [
			{
				required: true,
				errorMessage: '请输入密码'
			}
		],
		// 当前表单域的字段中文名，可不填写
		label: '密码',
		validateTrigger: 'submit'
	},
	role: {
		rules: [
			{
				required: true,
				errorMessage: '请选择角色'
			}
		],
		// 当前表单域的字段中文名，可不填写
		label: '角色',
		validateTrigger: 'submit'
	}
})

const loginForm = ref(null)

onReady(() => {
	loginForm.value.setRules(rules.value)
})

const checkLogin = e => {
	uni.showLoading()
	loginLoading.value = true
	console.log('submitLogin: ', loginFormData.value)
	loginForm.value
		.validate()
		.then(res => {
			console.log(res)
			uni.hideLoading()
			submitLogin()
		})
		.catch(err => {
			console.log(err)
			uni.hideLoading()
		})
}

const submitLogin = async () => {
	const { name, password, role } = loginFormData.value

	const params = {
		name,
		password,
		role
	}

	try {
		if (role === 'student') {
			setTimeout(() => {
				//正常到首页
				const url = `/pages/student/index`
				uni.redirectTo({
					url
				})
			}, 1000)
		} else {
			setTimeout(() => {
				//正常到首页
				const url = `/pages/teacher/index`
				uni.redirectTo({
					url
				})
			}, 1000)
		}
	} catch (e) {
		console.log(e)
	}
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
